package com.software.levelupandroid.taskShow.viewModel;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.software.levelupandroid.entity.Resource;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.home.CallBack;
import com.software.levelupandroid.taskShow.model.TaskShowRepository;

import java.util.List;

/**
 * @Description TODO
 * @Author LiangYaJie
 * @CreateTime 2024年05月29日 11:31:16
 */
public class TaskShowViewModel extends ViewModel {

    private final MutableLiveData<Resource<List<Task>>> taskListLiveData;

    public TaskShowViewModel(){
        taskListLiveData = new MutableLiveData<>();
    }

    public LiveData<Resource<List<Task>>> getTaskListLiveData() {
        return taskListLiveData;
    }

    public void getTaskListByStatus(Context context, int status){
        TaskShowRepository.getTaskShowRepository().getAllTasksByStatus(new CallBack<List<Task>>() {
            @Override
            public void onSuccess(List<Task> data) {
                runOnMainThread(taskListLiveData, Resource.success(data));
            }

            @Override
            public void onFailure(String msg) {
                Log.e("home:", msg);
                runOnMainThread(taskListLiveData, Resource.failure(msg, null));
            }
        }, context, status);
    }

    /**
     * 将LiveData的赋值放在主线程上
     * @param taskListLiveData
     * @param data
     */
    private void runOnMainThread(MutableLiveData<Resource<List<Task>>> taskListLiveData, Resource<List<Task>> data) {
        if (Looper.myLooper() == Looper.getMainLooper())
            //当前线程在主线程
            taskListLiveData.setValue(data);
        else
            //当前线程不在主线程
            taskListLiveData.postValue(data);
    }

}
